<?php

/**
 * create by nirunfa 2015-12-20
 * 
 * 公共方法库
 */


/**
 * 系统公共库文件
 * 主要定义系统公共函数库
 */



/**
 * 字符串转换为数组，主要用于把分隔符调整到第二个参数
 * @param  string $str  要分割的字符串
 * @param  string $glue 分割符
 * @return array
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function str2arr($str, $glue = ','){
	return explode($glue, $str);
}

/**
 * 数组转换为字符串，主要用于把分隔符调整到第二个参数
 * @param  array  $arr  要连接的数组
 * @param  string $glue 分割符
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function arr2str($arr, $glue = ','){
	return implode($glue, $arr);
}

/**
 * 字符串截取，支持中文和其他编码
 * @static
 * @access public
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 * @return string
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
	if(function_exists("mb_substr"))
		$slice = mb_substr($str, $start, $length, $charset);
	elseif(function_exists('iconv_substr')) {
		$slice = iconv_substr($str,$start,$length,$charset);
		if(false === $slice) {
			$slice = '';
		}
	}else{
		$re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
		$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
		$re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
		$re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
		preg_match_all($re[$charset], $str, $match);
		$slice = join("",array_slice($match[0], $start, $length));
	}
	return $suffix ? $slice.'...' : $slice;
}

/**
 * 系统加密方法
 * @param string $data 要加密的字符串
 * @param string $key  加密密钥
 * @param int $expire  过期时间 单位 秒
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function think_encrypt($data, $key = '', $expire = 0) {
	$key  = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
	$data = base64_encode($data);
	$x    = 0;
	$len  = strlen($data);
	$l    = strlen($key);
	$char = '';

	for ($i = 0; $i < $len; $i++) {
		if ($x == $l) $x = 0;
		$char .= substr($key, $x, 1);
		$x++;
	}

	$str = sprintf('%010d', $expire ? $expire + time():0);

	for ($i = 0; $i < $len; $i++) {
		$str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1)))%256);
	}
	return str_replace(array('+','/','='),array('-','_',''),base64_encode($str));
}

/**
 * 系统解密方法
 * @param  string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @param  string $key  加密密钥
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function think_decrypt($data, $key = ''){
	$key    = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
	$data   = str_replace(array('-','_'),array('+','/'),$data);
	$mod4   = strlen($data) % 4;
	if ($mod4) {
		$data .= substr('====', $mod4);
	}
	$data   = base64_decode($data);
	$expire = substr($data,0,10);
	$data   = substr($data,10);

	if($expire > 0 && $expire < time()) {
		return '';
	}
	$x      = 0;
	$len    = strlen($data);
	$l      = strlen($key);
	$char   = $str = '';

	for ($i = 0; $i < $len; $i++) {
		if ($x == $l) $x = 0;
		$char .= substr($key, $x, 1);
		$x++;
	}

	for ($i = 0; $i < $len; $i++) {
		if (ord(substr($data, $i, 1))<ord(substr($char, $i, 1))) {
			$str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
		}else{
			$str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
		}
	}
	return base64_decode($str);
}

/**
 * 数据签名认证
 * @param  array  $data 被认证的数据
 * @return string       签名
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function data_auth_sign($data) {
	//数据类型检测
	if(!is_array($data)){
		$data = (array)$data;
	}
	ksort($data); //排序
	$code = http_build_query($data); //url编码并生成query字符串
	$sign = sha1($code); //生成签名
	return $sign;
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function format_bytes($size, $delimiter = '') {
	$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
	for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
	return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 设置跳转页面URL
 * 使用函数再次封装，方便以后选择不同的存储方式（目前使用cookie存储）
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function set_redirect_url($url){
	cookie('redirect_url', $url);
}

/**
 * 获取跳转页面URL
 * @return string 跳转页URL
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function get_redirect_url(){
	$url = cookie('redirect_url');
	return empty($url) ? __APP__ : $url;
}

/**
 * 处理插件钩子
 * @param string $hook   钩子名称
 * @param mixed $params 传入参数
 * @return void
 */
function hook($hook,$params=array()){
	\Think\Hook::listen($hook,$params);
}

/**
 * 获取插件类的类名
 * @param strng $name 插件名
 */
function get_addon_class($name){
	$class = "Addons\\{$name}\\{$name}Addon";
	return $class;
}

/**
 * 获取插件类的配置文件数组
 * @param string $name 插件名
 */
function get_addon_config($name){
	$class = get_addon_class($name);
	if(class_exists($class)) {
		$addon = new $class();
		return $addon->getConfig();
	}else {
		return array();
	}
}

/**
 * 插件显示内容里生成访问插件的url
 * @param string $url url
 * @param array $param 参数
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function addons_url($url, $param = array()){
	$url        = parse_url($url);
	$case       = C('URL_CASE_INSENSITIVE');
	$addons     = $case ? parse_name($url['scheme']) : $url['scheme'];
	$controller = $case ? parse_name($url['host']) : $url['host'];
	$action     = trim($case ? strtolower($url['path']) : $url['path'], '/');

	/* 解析URL带的参数 */
	if(isset($url['query'])){
		parse_str($url['query'], $query);
		$param = array_merge($query, $param);
	}

	/* 基础参数 */
	$params = array(
			'_addons'     => $addons,
			'_controller' => $controller,
			'_action'     => $action,
	);
	$params = array_merge($params, $param); //添加额外参数

	return U('Addons/execute', $params);
}

/**
 * 时间戳格式化
 * @param int $time
 * @return string 完整的时间显示
 * @author huajie <banhuajie@163.com>
 */
function time_format($time = NULL,$format='Y-m-d H:i'){
	$time = $time === NULL ? NOW_TIME : intval($time);
	return date($format, $time);
}

   

/*写文件*/
function write_file_aomai($file_name,$content){
	 $filename = $file_name.'.txt';
	 $Ts=fopen($filename,"a");
	 fwrite($Ts,date('Y-m-d H:i:s',time()).": ".$content."\r\n");
	 fclose($Ts);
}
 
/**
 * 检查和更新公众号的access_token
 *
 * 需要进行异常处理
 */
/*本方法验证放在这里验证没通过，在控制器里执行没问题
 function check_update_mp_access_token($token,$appid,$appsecret,$access_token,$access_expires_in,$access_update_time){
 if(empty($access_token) || empty($access_update_time) || (time() - $access_update_time - 10) >= $access_expires_in){
 //获取access_token
 $url_get='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
 $json=json_decode(curlGet($url_get));
 if ($json->errmsg){
 throw new \Exception('获取access_token发生错误：错误代码'.$json->errcode.',微信返回错误信息：'.$json->errmsg);
 }
 $access_token = $json->access_token;
 $access_expires_in = $json->expires_in;
 //更新会数据库
 $data = array();
 $data['access_token']= $access_token;
 $data['access_expires_in']= $access_expires_in;
 $data['access_update_time']= time();

 M("mp_set")->where(array('token'=>$token))->save($data);
 }
 return $access_token;
 }
 */
function curlGet($url){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$url);
	//  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
	//  curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	$temp = curl_exec($ch);
	curl_close($ch);
	return $temp;
}

function curlPost($url,$data){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$url);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	$temp = curl_exec($ch);
	curl_close($ch);
	return $temp;
}

//by nirunfa
/**
 * 澳买解密方法
 * $txt 需要解密的字符串
 * $encrypt_key 传入的 key
 * */
function aomai_en_cryption_function( $txt, $encrypt_key ){
	$encrypt_key = md5( $encrypt_key );
	$ctr = 0;
	$tmp = "";
	$i = 0;

	for ( ; $i < strlen( $txt ); ++$i ){
		if ( $ctr == strlen( $encrypt_key ) ){
			$ctr = 0;
		}
		$tmp .= substr( $encrypt_key, $ctr, 1 ) ^ substr( $txt, $i, 1 );
		++$ctr;
	}
	return $tmp;
}

/**
 * 澳买解密方法
 * $txt 需要解密的字符串
 * */
function aomai_de_cryption($txt){
	$key=C('B2C_AUTH_KEY');
	$txt = aomai_en_cryption_function( base64_decode( $txt ), $key );
	$tmp = "";
	$i = 0;
	for ( ; $i < strlen( $txt ); ++$i ){
		$md5 = substr( $txt, $i, 1 );

		++$i;
		$tmp .= substr( $txt, $i, 1 ) ^ $md5;
	}
	return $tmp;
}

/**
 * 澳买加密方法
 * $txt 需要加密的字符串
 * */
function aomai_en_cryption($txt) {
	$tmp = "";
	$key=C('B2C_AUTH_KEY');
	for($i = 0;$i<strlen($txt);$i++){
		$tmp .= substr($txt, $i, 1) .chr(0);
	}
	return base64_encode(aomai_en_cryption_function($tmp, $key));
}
/*
 *链接B2C的数据库
 */
function BM($model){
	return M($model,C('B2C_DB_PREFIX'),'DB_CONFIG_B2C');
}

function OM($model){
	return M($model,C('O2O_DB_PREFIX'),'DB_CONFIG_O2O');
}

// 获取当前访问域名
// 2014-6-25 add by longy
function _get_Host_Name(){
	return "http://".$_SERVER['HTTP_HOST'];
}



/**
 * 对查询结果集进行排序
 * @access public
 * @param array $list 查询结果
 * @param string $field 排序的字段名
 * @param array $sortby 排序类型
 * asc正向排序 desc逆向排序 nat自然排序
 * @return array
 */
function list_sort_by($list,$field, $sortby='asc') {
	if(is_array($list)){
		$refer = $resultSet = array();
		foreach ($list as $i => $data)
			$refer[$i] = &$data[$field];
		switch ($sortby) {
			case 'asc': // 正向排序
				asort($refer);
				break;
			case 'desc':// 逆向排序
				arsort($refer);
				break;
			case 'nat': // 自然排序
				natcasesort($refer);
				break;
		}
		foreach ( $refer as $key=> $val)
			$resultSet[] = &$list[$key];
		return $resultSet;
	}
	return false;
}

/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 *
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {
	// 创建Tree
	$tree = array();
	if(is_array($list)) {
		// 创建基于主键的数组引用
		$refer = array();
		foreach ($list as $key => $data) {
			$refer[$data[$pk]] =& $list[$key];
		}
		foreach ($list as $key => $data) {
			// 判断是否存在parent
			$parentId =  $data[$pid];
			if ($root == $parentId) {
				$tree[] =& $list[$key];
			}else{
				if (isset($refer[$parentId])) {
					$parent =& $refer[$parentId];
					$parent[$child][] =& $list[$key];
				}
			}
		}
	}
	return $tree;
}

/**
 * 将list_to_tree的树还原成列表
 * @param  array $tree  原来的树
 * @param  string $child 孩子节点的键
 * @param  string $order 排序显示的键，一般是主键 升序排列
 * @param  array  $list  过渡用的中间数组，
 * @return array        返回排过序的列表数组
 * @author yangweijie <yangweijiester@gmail.com>
 */
function tree_to_list($tree, $child = '_child', $order='id', &$list = array()){
	if(is_array($tree)) {
		$refer = array();
		foreach ($tree as $key => $value) {
			$reffer = $value;
			if(isset($reffer[$child])){
				unset($reffer[$child]);
				tree_to_list($value[$child], $child, $order, $list);
			}
			$list[] = $reffer;
		}
		$list = list_sort_by($list, $order, $sortby='asc');
	}
	return $list;
}
/*
 *在sql语句里得到当前表名
 * Parameters $tablenme 表名
 * add by longy 2014-9-27
 */
function CTN($tablename){
	return C('DB_PREFIX').$tablename;
}


 

//获取品牌的方法【带缓存】
function _get_brand_forcache($id,$field_value=''){

    $datalist=S('js_brand_list_forcache');
    if(!$datalist){

        $entitylist=  M('brand')->select();
        $data=array();
        foreach($entitylist as $key=>$value){
            $data[$value['brand_id']]=$value;
        }
        $datalist=$data;
        S('js_brand_list_forcache',$datalist);
    }

    //得到 id 的对象
    $retarr= $datalist[$id];
     
    if(!empty($field_value))
    {
        //只返回得到的字段值
        $retarr=$retarr[$field_value];
    }

    return $retarr;


}
  
//获取分类的方法【带缓存】
function _get_category_forcache($id,$field_value=''){

    $datalist=S('js_category_list_forcache');
    if(!$datalist){

        $entitylist=  M('category')->select();
        $data=array();
        foreach($entitylist as $key=>$value){
            $data[$value['cat_id']]=$value;
        }
        $datalist=$data;
        S('js_category_list_forcache',$datalist);
    }
 
    
    //得到 id 的对象
    $retarr= $datalist[$id];
     
    if(!empty($field_value))
    {
        //只返回得到的字段值
        $retarr=$retarr[$field_value];
    }

    return $retarr;


}

/*
 * 从缓存里加载省市区对象
 * */
function _region_listforcach($region_id,$field_value=''){

    $regions=S('js_regions_forcache');
    if(!$regions){

        $regions=  M('region')->select();
        $data=array();
        foreach($regions as $key=>$value){
            $data[$value['region_id']]=$value;
        }
        $regions=$data;
        S('js_regions_forcache',$regions);
    }

    //得到 $region_id 的对象
    $retarr= $regions[$region_id];
    if(!empty($field_value))
    {
        //只返回得到的字段值
        $retarr=$retarr[$field_value];
    }

    return $retarr;


}
 

//设置商品路径
function _set_goods_imgpath($goods_img){
    return "/attas/".$goods_img;
}


  

/*
 * 清除缓存
 * */
function _clear_s_cache($module){
 
    if($module=='suppliers'){
        S('js_suppliers_list_forcache',NULL);
    }elseif($module=='category'){
        S('js_category_list_forcache',NULL);
    }elseif($module=='brand'){
        S('js_brand_list_forcache',NULL);
    }
    elseif($module=='tax_rate_policy'){
        S('js_tax_rate_policy_list_forcache',NULL);
    }
    elseif($module=='country'){
        S('js_country_list_forcache',NULL);
    }
    elseif($module=='shop_config'){
        S('js_shop_config_forcache',NULL);
    }

}



//获取系统配置【带缓存】
function _get_shop_config_forcache($id,$field_value=''){

    $datalist=S('js_shop_config_forcache');
    if(!$datalist){

        $entitylist=  M('shop_config')->select();
        $data=array();
        foreach($entitylist as $key=>$value){
            $data[$value['code']]=$value;
        }
        $datalist=$data;
        S('js_shop_config_forcache',$datalist);
    }

    //得到 id 的对象
    $retarr= $datalist[$id];
     
    if(!empty($field_value))
    {
        //只返回得到的字段值
        $retarr=$retarr[$field_value];
    }

    return $retarr;


}

/**
* post提交数据
* */
function aomai_Post_action_normals($url,$data){ // 模拟提交数据函数

    include_once ($_SERVER["DOCUMENT_ROOT"] . '/includes/Asyn/AomaiAsynPrg.php');   
    $execs = new AomaiAsynPrg(); 
    $execs->asynrun($url,$data);
    
}
        


function _CTN($model){
	return C('DB_PREFIX').$model;
}

/**
 * 根据数组中的某个键值大小进行排序，仅支持二维数组
 *
 * @param array $array 排序数组
 * @param string $key 键值
 * @param bool $asc 默认正序
 * @return array 排序后数组
 */
function arraySortByKey(array $array, $key, $asc = true)
{
	$result = array();
	// 整理出准备排序的数组
	foreach ( $array as $k => &$v ) {
		$values[$k] = isset($v[$key]) ? $v[$key] : '';
	}
	unset($v);
	// 对需要排序键值进行排序
	$asc ? asort($values) : arsort($values);
	// 重新排列原有数组
	foreach ( $values as $k => $v ) {
		$result[$k] = $array[$k];
	}

	return $result;
}

/*
 * 统计数据库连接对象
 */
function _TM($model){
	return M($model,C('TONGJI_DB_PREFIX'),C('TONGJI_DB_CONFIG'));
}

/*
 * 进销存数据库连接对象
 */
function JXCM($model){
    return M($model,C('JXCM_DB_PREFIX'),'DB_CONFIG_JXCM');
}

/*
 * 澳买网数据库连接对象
 */
function AoMai($model){
	return M($model,C('Aomai_DB_PREFIX'),'DB_CONFIG_AoMai');
}

 

/*
 * 生成日志文件
 * $pay_type 日志文件名称
 * $content 日志内容
 */
function write_file_aomai_ftp($pay_type,$content){
    $filename =$_SERVER['DOCUMENT_ROOT']. '/am_pay_log/aomai_logs/'.$pay_type.date('Y-m-d').'.txt';
    $Ts=fopen($filename,"a+");
    fputs($Ts,"\r\n".date('Y-m-d H:i:s',time()).' - '.$content);
    fclose($Ts);
}

/*
 * 生成日志文件-版本2
 * $pay_type 日志文件名称
 * $dir_name 目录名称
 * $content 日志内容
 */
function write_file_aomai_ftp_v2($pay_type,$dir_name,$content){
	$path = $_SERVER['DOCUMENT_ROOT']. '/am_pay_log/'.$dir_name;	
	if( !is_dir($path) ){
		mkdir($path);
	}
	
    $filename = $path.'/'.$pay_type.date('Y-m-d').'.txt';
    $Ts=fopen($filename,"a+");
    fputs($Ts,"\r\n".date('Y-m-d H:i:s',time()).' - '.$content);
    fclose($Ts);
}

//保存base64图片到指定目录
function  create_img_by_base64_for_tp($base64_str,$path){

	$base64_body = substr(strstr($base64_str,','),1);//删除头部
	$data= base64_decode($base64_body );

	//上传图片【身份证正面图片】
	file_put_contents($path, $data);

	//缩小图片的插件
	include_once($_SERVER['DOCUMENT_ROOT'].'/plugins/upload_file_rsize.php');

	//缩小图片
	$show_pic_scal=show_pic_scal(600, $path);
	resize($path,$show_pic_scal[0],$show_pic_scal[1]);

}

/*
 * 给身份证图片加上“清关水印”
 * */
function aomai_makemarkweak($imgFileName){

	include_once($_SERVER['DOCUMENT_ROOT'] . '/create_watermark.php');

	// 原始图片
	$img1 = $imgFileName;
	// 水印后的图片
	$img2 = $imgFileName;
	// 水印
	$water = $_SERVER['DOCUMENT_ROOT'] .'/themes/azmmshoptpl_red/images/qing.png';
	$img = new \image();
	//// 等比缩放
	//    $img->param($img1)->thumb($imgFileName, 800,800,0);
	//// center center 裁剪
	//            $img->param($img1)->thumb('./image/test_1.jpg', 200,200,1);
	//// top left 裁剪
	//            $img->param($img1)->thumb('./image/test_2.jpg', 200,200,2);
	// 右下角添加水印
	$img->param($img1)->water($img2,$water,5);

}

  
//生成唯一guid
function getGuid() {
	$charid = strtoupper(md5(uniqid(mt_rand(), true)));	
	$hyphen = chr(45);// "-"
	$uuid = substr($charid, 0, 8).$hyphen
	.substr($charid, 8, 4).$hyphen
	.substr($charid,12, 4).$hyphen
	.substr($charid,16, 4).$hyphen
	.substr($charid,20,12);
	return $uuid;
}

function getCode() {
	$charid = strtoupper(md5(uniqid(mt_rand(), true))); 
	
	$uuid = substr($charid, 0, 8)
	.substr($charid, 8, 4)
	.substr($charid,12, 4)
	.substr($charid,16, 4)
	.substr($charid,20,12);
	return $uuid;
} 

//创建cache文件
 function buildCache($cachefilename,$result,$flg=true) {  
	$cache_content = ($flg?"\xEF\xBB\xBF":"")."<?php\n". $result . "\n?>";
	updateCache ($cachefilename, $cache_content );  
} 

//创建file文件
 function buildFile($cachefilename,$result,$flg=true) {  
	$cache_content = ($flg?"\xEF\xBB\xBF":"")."\n". $result . "\n";
	updateCache($cachefilename, $cache_content );  
} 
 

function updateCache($path, $result) {
	$path_parts = pathinfo ( $path );
	if (! is_dir ( $path_parts ['dirname'] )) {
		if (! mk_dir ( $path_parts ['dirname'] )) {
			throw new Exception ( get_class ( $this ) . ' Error At Line ' . __line__ . ': Can not creat folder ' . $path_parts ['dirname'], 3 );
		}
	}
	if (file_exists ( $path )) {
		if (! unlink ( $path )) {
			throw new Exception ( get_class ( $this ) . ' Error At Line ' . __line__ . ': Can not delete old cache file ' . $path, 3 );
		}
	}
	if (! ($fp = @fopen ( $path, 'w' ))) {
		throw new Exception ( get_class ( $this ) . ' Error At Line ' . __line__ . ': Can not create cache file ' . $path, 3 );
	}
	if (! fwrite( $fp, $result )) {
		throw new Exception ( get_class ( $this ) . ' Error At Line ' . __line__ . ': Can not write cache file ' . $path, 3 );
	}
	fclose ( $fp );
}


function mk_dir($dir, $mode = 0755) {
	if (is_dir ( $dir ) || @mkdir ( $dir, $mode ))
		return true;
	if (! mk_dir ( dirname ( $dir ), $mode ))
		return false;
	return @mkdir ( $dir, $mode );
}


//针对微信昵称编码存储,显示解码两个方法 
/*
 把用户输入的文本转义（主要针对特殊符号和emoji表情）
 */
function userTextEncode($str){
	if(!is_string($str))return $str;
	if(!$str || $str=='undefined')return '';

	$text = json_encode($str); //暴露出unicode
	$text = preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i",function($str){
		return addslashes($str[0]);
	},$text); //将emoji的unicode留下，其他不动，这里的正则比原答案增加了d，因为我发现我很多emoji实际上是\ud开头的，反而暂时没发现有\ue开头。
	return json_decode($text);
}
/*
 解码上面的转义
 */
function userTextDecode($str){
	$text = json_encode($str); //暴露出unicode
	$text = preg_replace_callback('/\\\\\\\\/i',function($str){
		return '\\';
	},$text); //将两条斜杠变成一条，其他不动
	return json_decode($text);
}

/*写文件*/
function write_file($file_name,$content){
    $filename = $file_name.'.txt';
    $Ts=fopen($filename,"a");
    fwrite($Ts,date('Y-m-d H:i:s',time()).": ".$content."\r\n");
    fclose($Ts);
}

/**
+----------------------------------------------------------
 * Export Excel | 2016.06.21
 * Author:HongPing <hongping626@qq.com>
+----------------------------------------------------------
 * @param $expTitle     string File name
+----------------------------------------------------------
 * @param $expCellName  array  Column name
+----------------------------------------------------------
 * @param $expTableData array  Table data
+----------------------------------------------------------
 */
function exportExcel($expTitle,$expCellName,$expTableData,$path){
	ob_clean();
    //$xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
    //$xlsTitle = $expTitle;//文件名称
	
    $fileName = $_SESSION['loginAccount'].date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
    $cellNum = count($expCellName);
    $dataNum = count($expTableData);
    vendor("PHPExcel.PHPExcel");
    $objPHPExcel = new PHPExcel();
    $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');

    $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));
    for($i=0;$i<$cellNum;$i++){
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
    }
    // Miscellaneous glyphs, UTF-8
    for($i=0;$i<$dataNum;$i++){
        for($j=0;$j<$cellNum;$j++){
            $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
        }
    }
    //1,直接生成一个文件
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
	//$path="./Public/Excel/".$xlsTitle."_".date("Y-m-d")."/";
	if(!mk_dir($path))
	{
		return ; 
	}
	//write_file_aomai_ftp("_excel",$path);
    $objWriter->save($path.$expTitle."-".date("Y-m-d").'.xls');
	return $path.$expTitle."-".date("Y-m-d").'.xls'; 

/*     header('pragma:public');
    header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
    header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    //write_file('time_records','end:'.date('Y-m-d H:i:s'));  */
    exit;
}



 //清除系统缓存
function clear_sys_cache(){
    $curl=_get_Host_Name()."/_clear_cache.php?act=clear_fajax";
    $ret= file_get_contents($curl);
    // echo $ret;
}


/*
 * 得到商品的待发货库存数量
 * */
function _get_goods_wait_sendgoods_stock($goods_id)
{
	if(empty($goods_id))
	{
		return 0;
	}

	$wait_sendgoods_stock = M('order_goods')->alias('og')
	->join(array(
		' INNER JOIN ki_order_info as oi on og.order_id = oi.order_id '
	))
	->where(array(
			'og.goods_id'=>$goods_id,
			'_string'=>' (oi.order_status=1 or oi.order_status=5 or oi.order_status=6) and (oi.shipping_status=0 or oi.shipping_status=3 or oi.shipping_status=5 or oi.shipping_status=4 ) '
	))
	->sum('goods_number');

	return intval($wait_sendgoods_stock);
}

/*
 * 得到传入商品的可售库存
 * */
function _get_goods_cansale_count($goods_id)
{
	if(empty($goods_id))
	{
		return 0;
	}

	//先得到商品的代发货库存
	$wait_sendgoods_stock= _get_goods_wait_sendgoods_stock($goods_id);

	//再得到实际库存
	$goods_number = M('goods')->where(array('goods_id'=>$goods_id))->getField('goods_number');

	//相减得到可售库存
	$goods_number=intval($goods_number)-$wait_sendgoods_stock;
	//如果可售库存小于0，则让当前可售=0
	if($goods_number<0)
	{
		$goods_number=0;
	}

	return intval($goods_number);

}



/**
 * 将GMT时间戳格式化为用户自定义时区日期
 *
 * @param  string       $format
 * @param  integer      $time       该参数必须是一个GMT的时间戳
 *
 * @return  string
 */

function local_date($format, $time = NULL)
{
	$timezone = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : $GLOBALS['_CFG']['timezone'];

	if ($time === NULL)
	{
		$time = gmtime();
	}
	elseif ($time <= 0)
	{
		return '';
	}

	$time += ($timezone * 3600);

	return date($format, $time);
}

/**
 * 获得当前格林威治时间的时间戳
 *
 * @return  integer
 */
function gmtime()
{
	return (time() - date('Z'));
}

/**
 *  将一个用户自定义时区的日期转为GMT时间戳
 *
 * @access  public
 * @param   string      $str
 *
 * @return  integer
 */
function local_strtotime($str)
{
	$timezone = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : $GLOBALS['_CFG']['timezone'];

	/**
	 * $time = mktime($hour, $minute, $second, $month, $day, $year) - date('Z') + (date('Z') - $timezone * 3600)
	 * 先用mktime生成时间戳，再减去date('Z')转换为GMT时间，然后修正为用户自定义时间。以下是化简后结果
	 **/
	$time = strtotime($str) - $timezone * 3600;

	return $time;

}


